package com.fgs.common.widget;

import android.content.Context;
import android.content.res.TypedArray;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.LinearLayout;

import androidx.annotation.Nullable;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.fgs.common.R;
import com.fgs.common.adapter.CityAdapter;
import com.fgs.common.adapter.SelectedCityAdapter;
import com.fgs.common.entity.region.AreaInfo;
import com.fgs.common.entity.region.CityInfo;
import com.fgs.common.entity.region.ProvinceInfo;
import com.fgs.common.other.RegionData;
import com.fgs.common.entity.region.RegionInfo;
import com.fgs.common.utils.LogUtil;
import com.fgs.common.utils.ToastUtil;
import com.xuexiang.xui.adapter.recyclerview.RecyclerViewHolder;

import org.yczbj.ycrefreshviewlib.item.RecycleViewItemLine;

import java.util.ArrayList;
import java.util.List;

/**
 * @author fgs
 * @date 2020/8/13
 * @description
 **/
public class PlaceSelectView extends LinearLayout {

    private RecyclerView placeRecyclerView;
    private RecyclerView provinceRecyclerView;
    private RecyclerView cityRecyclerView;
    private RecyclerView areaRecyclerView;

    private SelectedCityAdapter placeAdapter;
    private CityAdapter provinceAdapter;
    private CityAdapter cityAdapter;
    private CityAdapter areaAdapter;
    private View view;
    private int mType;

    private OnPlaceConditionSelectListener onPlaceConditionSelectListener;


    private String province = "";
    private String city = "";
    private String area = "";
    private ProvinceInfo provinceInfo;
    private CityInfo cityInfo;
    private AreaInfo areaInfo;

    private int provincePosition;
    private boolean mHasLoaded;
    private boolean mIsShowSelectStatus;

    public PlaceSelectView(Context context) {
        this(context, null);
    }

    public PlaceSelectView(Context context, @Nullable AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public PlaceSelectView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.PlaceSelectView);
        try {
            mIsShowSelectStatus = typedArray.getBoolean(R.styleable.PlaceSelectView_PlaceSelectIsShowSelectStatus, false);
            mType = typedArray.getInteger(R.styleable.PlaceSelectView_PlaceSelectType, RegionData.TYPE_NORMAL);
        } finally {
            typedArray.recycle();
        }
        initView();
    }

    public void setOnPlaceConditionSelectListener(OnPlaceConditionSelectListener onPlaceConditionSelectListener) {
        this.onPlaceConditionSelectListener = onPlaceConditionSelectListener;
    }

    public View getPlaceConditionView() {
        return view;
    }


    private void initView() {

        mHasLoaded = RegionData.getInstance().loadProvinceData(mType);
        view = LayoutInflater.from(getContext()).inflate(R.layout.layout_city_select_new, null);
        placeRecyclerView = view.findViewById(R.id.layout_city_select_placeRecyclerView);
        provinceRecyclerView = view.findViewById(R.id.layout_city_select_provinceRecyclerView);
        cityRecyclerView = view.findViewById(R.id.layout_city_select_cityRecyclerView);
        areaRecyclerView = view.findViewById(R.id.layout_city_select_areaRecyclerView);
        LinearLayoutManager linearLayoutManager;
        RecycleViewItemLine itemLine;

        if (mIsShowSelectStatus) {//是否显示当前选择的区域
            placeRecyclerView.setVisibility(View.VISIBLE);
        } else {
            placeRecyclerView.setVisibility(View.GONE);
        }

        //选择状态
        placeAdapter = new SelectedCityAdapter(getContext());
        linearLayoutManager = new LinearLayoutManager(getContext());
        linearLayoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
        placeRecyclerView.setLayoutManager(linearLayoutManager);
        placeRecyclerView.setAdapter(placeAdapter);

        //省
        provinceAdapter = new CityAdapter<ProvinceInfo>();
        linearLayoutManager = new LinearLayoutManager(getContext());
        linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        provinceRecyclerView.setLayoutManager(linearLayoutManager);
        provinceRecyclerView.setAdapter(provinceAdapter);

//        itemLine = new RecycleViewItemLine(getContext(), LinearLayout.HORIZONTAL, (int) AppUtils.convertDpToPixel(1), getContext().getResources().getColor(R.color.colorGrayFour));
//        provinceRecyclerView.addItemDecoration(itemLine);


        //市
        cityAdapter = new CityAdapter<CityInfo>();
        linearLayoutManager = new LinearLayoutManager(getContext());
        linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        cityRecyclerView.setLayoutManager(linearLayoutManager);
        cityRecyclerView.setAdapter(cityAdapter);

//        itemLine = new RecycleViewItemLine(getContext(), LinearLayout.HORIZONTAL, (int) AppUtils.convertDpToPixel(1), getContext().getResources().getColor(R.color.colorGrayFour));
//        cityRecyclerView.addItemDecoration(itemLine);

        //区
        areaAdapter = new CityAdapter<AreaInfo>();
        linearLayoutManager = new LinearLayoutManager(getContext());
        linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        areaRecyclerView.setLayoutManager(linearLayoutManager);
        areaRecyclerView.setAdapter(areaAdapter);
//        itemLine = new RecycleViewItemLine(getContext(), LinearLayout.HORIZONTAL, (int) AppUtils.convertDpToPixel(1), getContext().getResources().getColor(R.color.colorGrayFour));
//        areaRecyclerView.addItemDecoration(itemLine);


        provinceAdapter.select(-1);
        cityAdapter.select(-1);
        areaAdapter.select(-1);

        initListener();


        if (!mHasLoaded) {
            ToastUtil.showShortToast("数据加载中...");
            return;
        }

        //显示省份的数据
        provinceAdapter.clear();
        provinceAdapter.getData().addAll(RegionData.getInstance().getProvinceItems());


        //添加 选省份 选城市 选地区 状态
        List<RegionInfo> regionInfoList = new ArrayList<>();
        RegionInfo regionInfo;
        for (int i = 0; i < 3; i++) {
            regionInfo = new RegionInfo();
            regionInfo.level = i + 1 + "";
            regionInfoList.add(regionInfo);
        }
        placeAdapter.addAll(regionInfoList);


        LayoutParams layoutParams = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
        view.setLayoutParams(layoutParams);
        addView(view);
    }

    private void initListener() {

        provinceAdapter.setOnItemClickListener(new RecyclerViewHolder.OnItemClickListener<ProvinceInfo>() {
            @Override
            public void onItemClick(View itemView, ProvinceInfo item, int position) {

                int size = provinceAdapter.getItemCount();
                if (position> size){
                    return;
                }

                if (provinceAdapter.select(position)) {
                    province = provinceAdapter.getSelectContentString();
                    provinceInfo = item;
                }

                provincePosition = position;
                placeAdapter.setInSelectPosition(0);

                //选择省状态
                RegionInfo regionInfo = placeAdapter.getAllData().get(0);
                regionInfo.label = item.name;
                regionInfo.code = item.code;
                placeAdapter.notifyDataSetChanged();

                //清空上次选择的市数据
                cityAdapter.getData().clear();
                //加载对应的市数据
                if (mType == RegionData.TYPE_NATIONWIDE) {
                    if (position == 0) {
                        if (null != onPlaceConditionSelectListener) {
                            onPlaceConditionSelectListener.onSelect(provinceInfo, null, null);
                            onPlaceConditionSelectListener.onSelect("", "", "");
                        }
                    } else {
                        //显示全国时，该条目下的市，区数据为空，获取其他省份的市数据时，位置需要-1
                        cityAdapter.getData().addAll(RegionData.getInstance().getCityItems().get(position - 1));
                    }
                } else {
                    cityAdapter.getData().addAll(RegionData.getInstance().getCityItems().get(position));
                }
                cityAdapter.notifyDataSetChanged();
                clearCitySelect();
                clearAreaSelect();
                clearAreaData();
            }


        });

        cityAdapter.setOnItemClickListener(new RecyclerViewHolder.OnItemClickListener<CityInfo>() {
            @Override
            public void onItemClick(View itemView, CityInfo item, int position) {

                int size = cityAdapter.getItemCount();
                if (position> size){
                    return;
                }


                if (cityAdapter.select(position)) {
                    city = cityAdapter.getSelectContentString();
                    cityInfo = item;
                }
                placeAdapter.setInSelectPosition(1);
                clearAreaData();

                List<AreaInfo> lists;
                if (mType == RegionData.TYPE_NATIONWIDE) {
                    lists = RegionData.getInstance().getAreaItems().get(provincePosition - 1).get(position);
                } else {
                    lists = RegionData.getInstance().getAreaItems().get(provincePosition).get(position);
                }
                if (mType == RegionData.TYPE_PROVINCE) {
                    if (position != 0) {
                        if (lists != null && lists.size() > 0) {
                            areaAdapter.getData().addAll(lists);
                        }
                    } else {
                        if (null != onPlaceConditionSelectListener) {
                            onPlaceConditionSelectListener.onSelect(provinceInfo, cityInfo, areaInfo);
                            onPlaceConditionSelectListener.onSelect(province, city, area);
                            LogUtil.print("province-" + province + "-city-" + city + "-area-" + area);
                        }

                    }
                } else {
                    if (lists != null && lists.size() > 0) {
                        areaAdapter.getData().addAll(lists);
                    }
                }


                areaAdapter.notifyDataSetChanged();
                clearAreaSelect();

                //选择市状态
                RegionInfo regionInfo = placeAdapter.getAllData().get(1);
                regionInfo.label = item.name;
                regionInfo.code = item.code;
                placeAdapter.notifyDataSetChanged();

            }
        });

        areaAdapter.setOnItemClickListener(new RecyclerViewHolder.OnItemClickListener<AreaInfo>() {
            @Override
            public void onItemClick(View itemView, AreaInfo item, int position) {

                int size = areaAdapter.getItemCount();
                if (position> size){
                    return;
                }

                if (areaAdapter.select(position)) {
                    area = areaAdapter.getSelectContentString();
                    areaInfo = item;
                }

//                if (!TextUtils.isEmpty(city) && city.equals("全省")) {
//                    city = "";
//                }
                if (!TextUtils.isEmpty(area) && area.equals("全市")) {
                    area = "";
                }

                //选择区状态
                RegionInfo regionInfo = placeAdapter.getAllData().get(2);
                regionInfo.label = item.name;
                regionInfo.code = item.code;
                placeAdapter.notifyDataSetChanged();

                if (null != onPlaceConditionSelectListener) {
                    onPlaceConditionSelectListener.onSelect(provinceInfo, cityInfo, areaInfo);
                    onPlaceConditionSelectListener.onSelect(province, city, area);
                    LogUtil.print("province-" + province + "-city-" + city + "-area-" + area);
                }
            }
        });


    }

    //清除省数据的选中状态
    private void clearProvinceSelect() {
        provinceAdapter.select(-1);
    }

    //清除市数据的选中状态
    private void clearCitySelect() {
        cityAdapter.select(-1);
        placeAdapter.getAllData().get(1).label = "";
        placeAdapter.getAllData().get(2).label = "";
    }

    //清除区数据的选中状态
    private void clearAreaSelect() {
        areaAdapter.select(-1);
        placeAdapter.getAllData().get(2).label = "";
    }

    //清空区数据
    private void clearAreaData() {
        areaAdapter.getData().clear();
    }

    //清空省数据
    private void clearProvinceData() {
        provinceAdapter.getData().clear();
    }

    //清空市数据
    private void clearCityData() {
        cityAdapter.getData().clear();
    }

    public interface OnPlaceConditionSelectListener {
        void onSelect(String province, String city, String area);

        void onSelect(ProvinceInfo provinceInfo, CityInfo cityInfo, AreaInfo areaInfo);
    }
}
